﻿namespace ApiTemplate.Common
{
    /// <summary>
    /// 发送HTTP请求的助手类
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="timeout">超时时间（单位：秒）：默认超时时间30秒</param>
        /// <returns>返回类型为元祖，第一个参数为：请求结果；第二个参数为是否请求成功</returns>
        public static async Task<Tuple<string, bool>> GetAsync(string url, int timeout = 30)
        {
            try
            {
                HttpClient httpClient = new()
                {
                    Timeout = new TimeSpan(0, 0, timeout)
                };
                string result = await httpClient.GetStringAsync(url);
                return new Tuple<string, bool>(result, true);
            }
            catch (Exception ex)
            {
                return new Tuple<string, bool>(ex.Message, false);
            }
        }

        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="url">请求的url</param>
        /// /// <param name="data">参数：json格式</param>
        /// <param name="timeout">超时时间（单位：秒）：默认超时时间30秒</param>
        /// <returns>返回类型为元祖，第一个参数为：请求结果；第二个参数为是否请求成功</returns>
        public static async Task<Tuple<string, bool>> PostAsync(string url, string data, int timeout = 30)
        {
            try
            {
                HttpClient httpClient = new()
                {
                    Timeout = new TimeSpan(0, 0, timeout)
                };
                HttpContent content = new StringContent(data);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var httpResponse = await httpClient.PostAsync(url, content);
                if (httpResponse.StatusCode == HttpStatusCode.OK)
                {
                    string result = await httpResponse.Content.ReadAsStringAsync();
                    return new Tuple<string, bool>(result, true);
                }
                else
                {
                    return new Tuple<string, bool>(httpResponse.StatusCode.ToString(), false);
                }
            }
            catch (Exception ex)
            {
                return new Tuple<string, bool>(ex.Message, false);
            }
        }
    }
}
